package com.atguigu.day09;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;
import org.apache.kafka.clients.consumer.ConsumerConfig;

import static org.apache.flink.table.api.Expressions.$;

public class Flink07_TableAPI_Source_Kafka {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 连接Kafka获取topic中的数据

        Schema schema = new Schema();
        schema.field("id", DataTypes.STRING());
        schema.field("ts", DataTypes.BIGINT());
        schema.field("vc", DataTypes.INT());

        //连接文件
        tableEnv.connect(new Kafka()
                .version("universal")
        .topic("sensor")
                .startFromLatest()
                .property(ConsumerConfig.GROUP_ID_CONFIG,"0926")
                .property(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092")
        )
                //指定解析数据的方式
                .withFormat(new Csv())
                //指定映射到表中 这个表的字段和字段类型
                .withSchema(schema)
                //表名
                .createTemporaryTable("sensor");

        Table table = tableEnv.from("sensor");

        Table resultTable = table.where($("id").isEqual("sensor_1"))
                .select($("id"), $("ts"), $("vc"));

        tableEnv.toAppendStream(resultTable, Row.class).print();

        env.execute();
    }
}
